<template>
    <rx-layout>
        <div slot="left" width="280" showButton="true">
            <div class="rx-Jenkins-left">
                <div class="rx-Jenkins" @click="showTree=!showTree">
                    <my-icon :type="showTree?'iconicon-test49':'iconicon-test47'"></my-icon>
                    <my-icon class="rx-icon" type="iconwenjianziliao"></my-icon>
                    <span class="rx-Jenkins-name">Jenkins构建工具</span>
                </div>
                <div v-if="showTree" class="rx-Jenkins-tree">
                    <div class="rx-Jenkins-tree-list" @click="onSelect(node.id)" :class="[selectKey==node.id?'rx-Jenkins-hover':'']" v-for="node in jenkinsData" :key="node.id" :title="node.url">
                        <my-icon type="iconfile-text-fill" class="rx-tree-icon"></my-icon><span class="rx-tree-name">{{node.name}}</span>
                    </div>
                </div>
            </div>
        </div>
        <div slot="center" style>
            <rx-fit :isheader="false">
                <div slot="toolheader" foldbtn="false" border="false">
                    <div class="table-page-search-wrapper">
                        <a-form layout="inline">
                            <a-row :gutter="24">
                                <a-col :span="12">
                                    <a-form-item label="流水线名称">
                                        <a-input placeholder="请输入流水线名称" v-model="jobName"/>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="12">
                                        <span class="table-page-search-submitButtons">
                                            <a-button @click="search" icon="search" type="primary">{{$ti18('rxList.searchBtn','查询')}}</a-button>
                                            <a-button @click="resetSearch" style="margin-left: 4px">{{$ti18('rxList.resetBtn','重置')}}</a-button>
                                        </span>
                                </a-col>
                            </a-row>
                        </a-form>
                    </div>
                </div>
                <rx-grid
                    ref="table"
                    :bordered="true"
                    style="min-height:340px;"
                    :dataSource="searchJobs"
                    :columns="columns"
                    :showPage="false"
                >
                    <span slot="name" slot-scope="{ text, record }">
                        <a class="rx-grid-name" :href="record.url"  target="_blank">{{text}}<span class="rx-multiBranch" v-if="record.multiBranch">多分支</span></a>
                    </span>
                    <span slot="latestUserName" slot-scope="{ text, record }">
                        <div class="rx-latestUserName">
                            <div v-if="text" class="rx-user"><my-icon type="iconVue3_user"></my-icon></div>
                            <span :title="text">{{text}}</span>
                        </div>
                    </span>
                    <span slot="result" slot-scope="{ text, record }">
                        <a-tag :color="statusMap[text].color" v-if="text && statusMap[text]">
                          <span>{{ statusMap[text].text }}</span>
                        </a-tag>
                      </span>
                    <span slot="action"slot-scope="{ text, record }">
                        <span @click="runJob(record)">运行</span>
                        <span  @click="showDetails(record)" v-if="!record.multiBranch">查看明细</span>
                    </span>
                </rx-grid>
            </rx-fit>
        </div>
    </rx-layout>
</template>

<script>
/**
 * 流水线管理.
 */
import {Util} from "@lowcode/jpaas-common-lib"
import SysJenkinsApi from "@/api/system/core/sysJenkins";
import SysPipelineDetails from "./SysPipelineDetails.vue"
export default {
    name: "SysPipelineManage",
    data() {
        return {
            jenkinsData:[],
            //所有的流水线任务
            jenkinsJobs:[],
            //查询结果
            searchJobs:[],
            columns:[
                {title: this.$ti18('rxList.index', '序号'), type: 'indexColumn', width: 50, dataIndex: 'serial', scopedSlots: {customRender: 'serial'}},
                {title: "流水线名称", dataIndex: 'name', width: 160,scopedSlots: { customRender: 'name' }},
                {title: "最近运行状态", dataIndex: 'result', width: 80, scopedSlots: { customRender: 'result' }},
                {title: "持续时间", dataIndex: 'duration', width: 80},
                {title: "最近执行时间", dataIndex: 'latestTime', width: 100},
                {title: "最近运行人", dataIndex: 'latestUserName', width: 150,scopedSlots: { customRender: 'latestUserName' }},
                {title: "URL", dataIndex: 'url', width: 150},
                {key: 'action', title:  this.$ti18('rxList.action', '操作'), dataIndex: 'action', scopedSlots: { customRender: 'action' }, width: 180,},
            ],
            statusMap: {
                '': {color: '', text: ""},
                'SUCCESS': {color: 'green', text: "运行成功"},
                'FAILURE': {color: 'red', text: "运行失败"},
                'ABORTED': {color: 'grey', text: "运行中断"},
                'UNSTABLE': {color: 'orange', text: "警告"},
                'BUILDING': {color: 'blue', text: "编译中"},

            },
            //选择的构建器
            selectKey:"",
            //查询名称
            jobName:"",
            showTree:true,

        }
    },
    created() {
        this.getJenkinsData();
    },
    methods: {
        getJenkinsData(){
            SysJenkinsApi.getEnableList().then(res=>{
                this.jenkinsData =res || [];
            });
        },
        /**
         * 点击树
         * @param selectedKeys
         */
        onSelect(selectedKeys){
            this.selectKey = selectedKeys;
            this.jobName="";
            this.loadJenkinsJobs("");
        },
        loadJenkinsJobs(){
            if(!this.selectKey){
                this.$message.warn("请先选择左侧的构建器！");
                return;
            }
            //点击父级
            if(this.selectKey == "-1"){
                this.searchJobs = [];
                this.jenkinsJobs = [];
                return;
            }
            this.$refs.table.gridLoading = true;
            SysJenkinsApi.getAllJobs(this.selectKey).then(res=>{
                this.jenkinsJobs = res;
                this.searchJobs = res;
                this.$refs.table.gridLoading = false;
            })
        },
        search(){
            if(this.selectKey){
                if (!this.jobName) {
                    this.searchJobs = Util.deepClone(this.jenkinsJobs);
                    return;
                }
                let jobs = this.findByName(this.jenkinsJobs, this.jobName);
                this.searchJobs = Util.deepClone(jobs) || [];
            }else {
                this.loadJenkinsJobs();
            }
        },
        resetSearch(){
            this.jobName="";
            if(this.selectKey){
                this.searchJobs = Util.deepClone(this.jenkinsJobs);
            }else {
                this.loadJenkinsJobs();
            }
        },
        findByName(treeData, name) {
            let results = [];
            function search(node) {
                if (node && node.length > 0) {
                    for (let item of node) {
                        if (item.name && item.name.includes(name)) {
                            item.idx_ = Util.randomId();
                            results.push(item);
                        }
                        if (item.children && item.children.length > 0) {
                            search(item.children); // 递归搜索子节点
                        }
                    }
                }
            }
            search(treeData); // 开始搜索
            return results; // 返回所有找到的结果
        },
        /**
         * 运行
         * @param record
         */
        runJob(record){
            let content = "您确定要运行该流水线吗？";
            //多分支
            if(record.multiBranch){
                content = "该流水线为多分支，您确定要运行吗？";
            }
            let self_ =this;
            let parentPath = this.getParentPath(record.url,record.name);
            this.$confirm({
                title: self_.$ti18('rxMsa.actionTips','操作提示'),
                content: content,
                okText: self_.$ti18('rxForm.ackBtn', '确认'),
                cancelText: self_.$ti18('rxForm.cancelBtn', '取消'),
                zIndex: 20000,
                onOk() {
                    SysJenkinsApi.runJobByName({jobName:record.name,url:parentPath,builderId:record.builderId});
                },
                onCancel() {
                }
            })
        },
        /**
         * 查看明细
         * @param record
         */
        showDetails(record){
            Util.open({
                component: SysPipelineDetails,
                curVm: this,
                zIndex:999999,
                max:true,
                title: '流水线明细',
                data: {
                    pipeline:record
                }
            },  function (action,data) {
                if(action!="ok") return;
                extJson.dataSource=data;
                self.controlJson.extJson=extJson;
            })
        },
        getParentPath(urlString, jobName) {
            // 解析 URL
            const url = new URL(urlString);
            // 获取路径
            let path = url.pathname;
            // 查找子路径 "job/dev" 的位置
            const subPath = '/job/' + jobName;
            const subPathIndex = path.indexOf(subPath);
            // 如果找到了子路径，则截取父路径
            if (subPathIndex !== -1) {
                const newPath = path.slice(0, subPathIndex);
                return url.origin + newPath + '/';
            } else {
                // 如果没有找到子路径，则返回原始 URL
                return url.href;
            }
        },
    },
    watch: {}
}
</script>

<style scoped>
.rx-Jenkins-left{
    padding:10px 20px;
    overflow: auto;
}
.rx-Jenkins{
    display: flex;
    height: 32px;
    opacity: 1;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    cursor: pointer;
}
.rx-Jenkins-name{
    font-size: 14px;
    font-weight: 500;
    letter-spacing: 0px;
    line-height: 0px;
    color: rgba(0, 0, 0, 0.85);
    margin-left: 9px;
}
.rx-icon{
    color: rgba(255, 191, 67, 1);
    font-size: 20px;
    margin-left: 5px;
}
.rx-Jenkins-tree{
    margin-left: 32px;
}
.rx-Jenkins-tree-list{
    height: 32px;
    opacity: 1;
    border-radius: 4px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 0px 10px 0px 10px;
    cursor: pointer;
    margin-bottom:1px;
}
.rx-Jenkins-tree-list:hover{
    background: rgba(239, 245, 255, 1);
}
.rx-Jenkins-tree-list:hover .rx-tree-icon{
    color: rgba(66, 133, 244, 1);
}

.rx-Jenkins-tree-list:hover .rx-tree-name{
    color: rgba(66, 133, 244, 1);
}
.rx-Jenkins-hover{
    background: rgba(239, 245, 255, 1);
}
.rx-Jenkins-hover .rx-tree-icon,.rx-Jenkins-hover .rx-tree-name{
    color: rgba(66, 133, 244, 1);
}
.rx-tree-name{
    font-size: 14px;
    color: rgba(0, 0, 0, 0.85);
    overflow: hidden;
    flex: 1;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-left: 5px;
}
.rx-tree-icon{
    font-size: 20px;
    color: rgba(0, 0, 0, 0.2);
}
.rx-multiBranch{
    width: 56px;
    height: 21px;
    opacity: 1;
    border-radius: 24px;
    border: 1px solid rgba(232, 232, 232, 1);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 2px 10px 2px 10px;
    font-size: 12px;
    margin-left: 6px;
    color: rgba(0, 0, 0, 0.45);
}
.rx-grid-name{
    display: flex;
    align-items: center;
}
.rx-user{
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background: rgba(66, 133, 244, 1);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: white;
    margin-right: 6px;
}
.rx-latestUserName{
    display: flex;
    align-items: center;
}
.rx-latestUserName span{
    overflow: hidden;
    flex: 1;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>